package com.hmdp.common.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2023-01-19 16:59
 */
public class SimpleRedisLock implements ILock {

    private final StringRedisTemplate stringRedisTemplate;
    private final String KEY_NAME; //锁的键
    private final String Tid; //标识线程的唯一字符串
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("/lua/unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    public SimpleRedisLock(String key, String name, StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.KEY_NAME = RedisConstants.LOCK_KEY_PREFIX + key + name;
        Tid = UUID.randomUUID().toString(true) + "_" + Thread.currentThread().getId(); // 拼接 UUID 和线程ID
    }

    @Override
    public boolean tryLock(long timeSec) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(KEY_NAME, Tid, timeSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(aBoolean);
    }

    @Override
    public void unlock() {
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_NAME), Tid);

//        原始方法无法解决释放锁的原子性
//        if (UID.equals(stringRedisTemplate.opsForValue().get(KEY_NAME))) {
////            判断是不是自己的锁
//            stringRedisTemplate.delete(KEY_NAME);
//        }
    }

}
